<!--
 /**
 * Author: hongChengHao
 * Date: 2022-07-28 20:48
 * Desc: 生成海报
 */
-->
<template>
  <yy-page class="poster">
    <canvas
      v-if="!iscomplete"
      :style="{
        width: cansWidth + 'px',
        height: cansHeight + 'px'
      }"
      canvas-id="poster"
    ></canvas>
  </yy-page>
</template>
<script>
  export default {
    name: 'Poster',
    props: {
      obj: {
        type: Object,
        default: () => {
          return {}
        }
      }
    },
    data() {
      return {
        ctx: null,
        // cansWidth: 660,
        // cansHeight: 528,
        cansWidth: 300,
        cansHeight: 240,
        tempFilePath: '', // 生成路径
        iscomplete: false // 是否完成绘画
      }
    },
    async created() {
      await this.getUserInfo()
    },
    mounted() {
      this.ctx = uni.createCanvasContext('poster', this)
      this.drawposter()
    },
    methods: {
      // 开始绘画
      async drawposter() {
        uni.showLoading({
          title: '加载中...',
          mask: true
        })

        await this.drawWebImg({
          url: this.obj.image,
          x: 0,
          y: 0,
          width: this.cansWidth,
          height: this.cansHeight,
          aspectFit: true
        })

        await this.drawRect({
          color: '#fff',
          x: 0,
          y: 0,
          width: this.cansWidth,
          height: 30
        })
        await this.drawWebImg({
          url: this.avatar,
          x: 10,
          y: 0,
          width: 25,
          height: 25
        })
        await this.drawText({
          text: this.nickName,
          x: 40,
          y: 17,
          color: '#000',
          size: 13,
          bold: true
        })

        await this.drawRect({
          color: 'rgba(0, 0, 0, 0.5)',
          x: 0,
          y: 180,
          width: 300,
          height: 60
        })
        const text = ['coupon', 'normal'].includes(this.obj.type) ? '立即购买' : '去看看'
        await this.drawText({
          text: text,
          x: 150,
          y: 215,
          color: '#fff',
          size: 20,
          bold: false,
          center: true
        })

        this.tempFilePath = await this.saveCanvs()
        this.iscomplete = true
        uni.hideLoading()
      },
      // 画图
      drawWebImg(conf) {
        return new Promise((resolve, reject) => {
          // 图片短边显示
          const aspectFit = (imageWidth, imageHeight, canvasWidth, canvasHeight) => {
            const imageRate = imageWidth / imageHeight
            const canvasRate = canvasWidth / canvasHeight
            let [sx, sy, sw, sh] = []
            if (imageRate >= canvasRate) {
              sw = imageHeight * canvasRate
              sh = imageHeight
              sx = (imageWidth - sw) / 2
              sy = 0
            } else {
              sh = imageWidth / canvasRate
              sw = imageWidth
              sx = 0
              sy = (imageHeight - sh) / 2
            }
            return [sx, sy, sw, sh]
          }
          uni.downloadFile({
            url: `${conf.url}?t=${Math.random().toString()}`,
            success: (res) => {
              uni.getImageInfo({
                src: res.tempFilePath,
                success: (image) => {
                  console.log(image.width)
                  console.log(image.height)
                  let imgArr = []
                  if (conf.aspectFit) {
                    imgArr = aspectFit(image.width, image.height, conf.width, conf.height)
                    this.ctx.drawImage(res.tempFilePath, imgArr[0], imgArr[1], imgArr[2], imgArr[3], conf.x, conf.y, conf.width ? conf.width : '', conf.height ? conf.height : '')
                  } else {
                    this.ctx.drawImage(res.tempFilePath, conf.x, conf.y, conf.width ? conf.width : '', conf.height ? conf.height : '')
                  }

                  this.ctx.draw(true, () => {
                    resolve()
                  })
                }
              })

              // console.log('this.ctx.drwaImage:', this.ctx.drwaImage)
            },
            fail: (err) => {
              uni.hideLoading()
              this.$msg.toast('链接失效，画图出错')
              reject(err, '画图出错')
            }
          })
        })
      },
      // 画矩形
      drawRect(conf) {
        return new Promise((resolve) => {
          this.ctx.restore()

          this.ctx.setFillStyle(conf.color)

          this.ctx.fillRect(conf.x, conf.y, conf.width, conf.height)

          this.ctx.draw(true, () => {
            this.ctx.save()
            resolve()
          })
        })
      },
      // 画文本
      drawText(conf) {
        return new Promise((resolve) => {
          this.ctx.restore()
          this.ctx.setFillStyle(conf.color)
          if (conf.bold) this.ctx.font = `normal bold ${conf.size}px sans-serif`
          this.ctx.setFontSize(conf.size)
          let x = conf.x

          if (conf.center) {
            const len = this.ctx.measureText(conf.text)
            x = this.cansWidth / 2 - len.width / 2 - 5
          }

          this.ctx.fillText(conf.text, x, conf.y)
          this.ctx.draw(true, () => {
            this.ctx.save()
            resolve()
          })
        })
      },
      // canvas 转 图片
      saveCanvs() {
        return new Promise((resolve, reject) => {
          uni.canvasToTempFilePath(
            {
              x: 0,
              y: 0,
              canvasId: 'poster',
              success: (res) => {
                // #ifdef H5
                this.$emit('getShareImage', this.obj.image)
                // #endif

                // #ifndef H5
                this.$emit('getShareImage', res.tempFilePath)
                // #endif
                resolve(res.tempFilePath)
              },
              fail: (err) => {
                uni.hideLoading()
                reject(err)
              }
            },
            this
          )
        })
      },
      // 获取用户信息
      getUserInfo() {
        this.nickName = this.$store.state.userInfo.nickName || ''
        this.avatar = this.$store.state.userInfo.headImg || 'https://public-oss-file.zmaxfilm.com/pre/image/png/2022072710245889141.png'
      }
    }
  }
</script>
<style lang="scss" scoped>
  .poster {
    position: relative;
  }
</style>
